package com.personal.core.xml;

import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

import com.personal.core.utils.ConvertUtil;

/**
 * xml转换工具类
 * @author cuibo
 *
 */
public class XMLConvertUtil
{
    
    /**
     * 节点转实体
     * @param element
     * @return
     */
    public static <T> T elementToObject(Element element, T t)
    {
        if (element == null || t == null)
        {
            return null;
        }
        Map<String, String> map = elementToMap(element);
        if (map == null)
        {
            return null;
        }
        return ConvertUtil.mapTObject(map, t);
    }
    
    /**
     * 节点转实体
     * @param element
     * @return
     */
    public static <T> T elementToObject(Element element, Class<T> t)
    {
        if (element == null || t == null)
        {
            return null;
        }
        Map<String, String> map = elementToMap(element);
        if (map == null)
        {
            return null;
        }
        return ConvertUtil.mapTObject(map, t);
    }
    
    
    /**
     * 节点转Map
     * @param element
     * @return
     */
    public static Map<String, String> elementToMap(Element element)
    {
        if (element == null)
        {
            return null;
        }
        Map<String, String> result = new HashMap<String, String>();
        NamedNodeMap map = element.getAttributes();
        for (int i = 0; i < map.getLength(); i++)
        {
            org.w3c.dom.Node node = map.item(i);
            result.put(node.getNodeName(), node.getNodeValue());
        }
        return result;
    }
}
